﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Windows.Forms;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Geometry;
using System.Data.SQLite;
using System.Data;
using System.Data.Common;
//using Autodesk.AutoCAD.GraphicsInterface;
using Autodesk.AutoCAD.PlottingServices;
//using Autodesk.AutoCAD.PlottingServices;
//using Application = Autodesk.AutoCAD.ApplicationServices.Core.Application;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Interop.Common;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using System.Threading;
using System.ComponentModel;

namespace cadbom
{
    class SelectBlock2Pdf
    {
        [DllImport("accore.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedTrans")]

        static extern int acedTrans(double[] point, IntPtr fromRb, IntPtr toRb, int disp, double[] result);
        public void PlotBlockColToPDF(Point3d first1,Point3d second2,String code)
        {
            String selectedProductCode = code;
            String OutPath = "";
            String processHandleId = "";
            Boolean checkProductCode = false;
            Directory.CreateDirectory(GValues.pdfPath);
            Dictionary<String, Dictionary<String, String>> tableDict = new Dictionary<string, Dictionary<string, string>>();
            SetObject setObject = new SetObject();
            setObject.initTableDictData(tableDict);
            // 判断文件是否存在
            //if (File.Exists(OutPath))
            //{
            //    try
            //    {
            //        // 尝试删除文件
            //        File.Delete(OutPath);
            //        outMsg.AddMsg("文件已删除。");
            //    }
            //    catch (IOException ex)
            //    {                    // IO异常处理
            //        outMsg.AddMsg("无法删除文件: " + ex.Message);
            //    }
            //}
            try
            {

                String BlockName;
                String PrinterName = "DWG To PDF.pc3";

                String PaperSize = "ISO_full_bleed_A4_(210.00_x_297.00_MM)";//"ISO_A4_(210.00_x_297.00_MM)";
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                Database db = doc.Database;
                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                //改成块开始
                //PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner of plot area: ");
                //ppo.AllowNone = false;
                //PromptPointResult ppr = ed.GetPoint(ppo);
                //if (ppr.Status != PromptStatus.OK)
                //    return;
                //Point3d first1 = ppr.Value;
                //PromptCornerOptions pco = new PromptCornerOptions("\nSelect second corner of plot area: ", first1);
                //ppr = ed.GetCorner(pco);
                //if (ppr.Status != PromptStatus.OK)
                //    return;
                //Point3d second2 = ppr.Value;
                //改成块结束

                ///wcs 2 ucs
                ///
                //Vector3d vect = db.Ucsorg.GetVectorTo(new Point3d(0,0,0));
                //Matrix3d matWCS2UCS = Matrix3d.WorldToPlane(vect);
                //Point3d second = second1.TransformBy(matWCS2UCS);
                //Point3d first = first1.TransformBy(matWCS2UCS);
                ////


                //Matrix3d wcs2ucs = doc.Editor.CurrentUserCoordinateSystem.Inverse();
                //Point3d ucsPoint = worldPoint.TransformBy(wcs2ucs);

                //wcs 2 dcs
                //
                //
                // Gets the current view
                //ViewTableRecord acView = doc.Editor.GetCurrentView();
                ////Extents3d eExtents = new Extents3d(new Point3d(0, 0, 0), new Point3d(630, 445.5, 0));
                //Extents3d eExtents = new Extents3d(first, second);
                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                               acView.ViewDirection,
                //                               acView.Target) * matWCS2DCS;

                //// Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);

                //
                //ViewTableRecord acView = doc.Editor.GetCurrentView();

                //Extents3d eExtents = new Extents3d(first, second);

                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                                acView.ViewDirection,
                //                                acView.Target) * matWCS2DCS;

                ////Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);
                //var wcsWindow = new Extents2d(eExtents.MinPoint.X, eExtents.MinPoint.Y,
                //                                        eExtents.MaxPoint.X, eExtents.MaxPoint.Y);

                //
                // 获取当前视图方向
                Vector3d viewDir = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;

                // 获取当前视图位置
                Point3d viewPos = ed.GetCurrentView().Target;

                // 构造视图变换矩阵
                Matrix3d viewTransform = Matrix3d.WorldToPlane(viewDir).Inverse();
                //viewTransform = Matrix3d.Displacement(viewPos.GetAsVector()) * viewTransform;

                //// 将WCS坐标转换为DCS坐标
                Point3d first = first1.TransformBy(viewTransform);
                Point3d second = second2.TransformBy(viewTransform);


                ///====

                // Transform from UCS to DCS
                ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                double[] firres = new double[] { 0, 0, 0 };
                double[] secres = new double[] { 0, 0, 0 };
                // Transform the first point...
                acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                // ... and the second
                acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                // We can safely drop the Z-coord at this stage
                Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                //Object SysVarBackPlot = Application.GetSystemVariable("BACKGROUNDPLOT");
                //Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                Transaction tr = db.TransactionManager.StartTransaction();
                using (tr)
                {
                    // 打开图层表
                    LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                    // 遍历所有图层
                    foreach (ObjectId layerId in lt)
                    {
                        // 打开图层表记录
                        LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForRead);

                        // 检查图层是否锁定
                        if (ltr.IsLocked)
                        {
                            // 解锁图层
                            ltr.UpgradeOpen();
                            ltr.IsLocked = false;
                            ltr.DowngradeOpen();
                        }
                    }
                    // We'll be plotting the current layout
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);

                    // 定义过滤条件，设置仅选择BlockReference

                    //SelectionFilter filter = new SelectionFilter(new TypedValue[]
                    //{
                    //    new TypedValue((int)DxfCode.Start, "TEXT") // "INSERT"代表图块引用
                    //});
                    // 使用选取窗口和过滤条件进行选择
                    PromptSelectionResult selectionResult = ed.SelectCrossingWindow(first, second);

                    // 检查选择结果
                    if (selectionResult.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage("\n未选择对象或操作取消。");
                        return;
                    }
                    //Dictionary<String, String> fieldDict = new Dictionary<string, string>();
                    SelectionSet sSet = selectionResult.Value;
                    ObjectId[] selectedIds = sSet.GetObjectIds();  // 获取选择对象的ObjectiID数组.
                    foreach (ObjectId objId in selectedIds)
                    {
                        Entity entity = tr.GetObject(objId, OpenMode.ForRead) as Entity;                      

                        if (entity is Table)
                        {

                            Table table = entity as Table;
                            // 你现在可以使用table对象了
                            // ...
                            processHandleId = table.Handle.Value.ToString();
                            if (table.XData != null)
                            {
                                Dictionary<String, String> xDataDict = new Dictionary<string, string>();
                                String tableType = "none";
                                ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                // 遍历ResultBuffer以查看数据
                                foreach (TypedValue tv in rb)
                                {
                                    switch ((DxfCode)tv.TypeCode)
                                    {
                                        case DxfCode.ExtendedDataRegAppName:
                                            var a = tv.Value.ToString();
                                            ed.WriteMessage("\n APP Code :" + a);
                                            break;
                                        case DxfCode.ExtendedDataAsciiString:
                                            var b = tv.Value.ToString();
                                            if (b.IndexOf("tableType:") != -1)
                                            {
                                                String[] cc = b.Split(':');
                                                if (cc[1] == "processSop")
                                                {
                                                    tableType = "processSop";
                                                    xDataDict["processSop"] = "true"; //SOP图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "processBom")
                                                {
                                                    tableType = "processBom";
                                                    xDataDict["processBom"] = "true"; //工艺图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "productBom")
                                                {
                                                    tableType = "productBom";
                                                    xDataDict["productBom"] = "true"; //产品图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                            }
                                            else if (b.IndexOf("processName:") != -1)
                                            {
                                                ed.WriteMessage("\n Process Name :" + b);
                                                String[] cc = b.Split(':');
                                                //selectedProcessName = cc[1];
                                                xDataDict["processName"] = cc[1];
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            else if (b.IndexOf("productCode:") != -1)
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                String[] cc = b.Split(':');
                                                //selectedProductCode = cc[1];
                                                xDataDict["productCode"] = cc[1];
                                                checkProductCode = true;
                                            }
                                            else
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                //selectedProductCode = b;
                                                checkProductCode = true;
                                                xDataDict["productCode"] = b;
                                                xDataDict["oldTable"] = "true";
                                                tableType = "oldTable";
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            break;
                                        // 其他类型的DXF组码...

                                    }
                                }
                                tableDict[tableType] = xDataDict;
                            }
                            else
                            {
                                ed.WriteMessage("\n实体没有扩展数据！");
                            }
                        }

                    }
                    if (!checkProductCode)
                    {
                        ed.WriteMessage("\n选择框内没有定义工艺数据！");
                        //return;
                    }
                    else
                    {
                        if (tableDict["productBom"]["productBom"] == "true" && tableDict["processBom"]["processBom"] == "false" && tableDict["processSop"]["processSop"] == "false")
                        {
                            ed.WriteMessage("\n选择框内没有定义工艺数据！");
                            //return;
                        }
                    }

                    Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                    if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                    {
                        PlotEngine pe = PlotFactory.CreatePublishEngine();
                        using (pe)
                        {
                            PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true);
                            using (ppd)
                            {
                                int numSheet = 1;
                                // Setting up the PlotProgress dialog
                                ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                                ppd.LowerPlotProgressRange = 0;
                                ppd.UpperPlotProgressRange = 100;
                                ppd.PlotProgressPos = 0;


                                ppd.OnBeginPlot();
                                ppd.IsVisible = true;
                                pe.BeginPlot(ppd, null);

                                ppd.StatusMsgString = "Plotting block 1";
                                ppd.OnBeginSheet(); //????
                                ppd.LowerSheetProgressRange = 0;
                                ppd.UpperSheetProgressRange = 100;
                                ppd.SheetProgressPos = 0;

                                PlotInfoValidator piv = new PlotInfoValidator();
                                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                PlotPageInfo ppi = new PlotPageInfo();
                                PlotInfo pi = new PlotInfo();
                                //BlockReference blk = gblk.BlockRef;
                                //Layout lo = btr.LayoutObj;

                                //// Getting coodinates of window to plot
                                //Extents3d ext = (Extents3d)blk.Bounds;
                                //Point3d first = ext.MaxPoint;
                                //Point3d second = ext.MinPoint;
                                //ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                                //double[] firres = new double[] { 0, 0, 0 };
                                //double[] secres = new double[] { 0, 0, 0 };
                                //acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                                //acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                                //Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                                // We need a PlotSettings object based on the layout settings which we then customize
                                PlotSettings ps = new PlotSettings(lo.ModelType);
                                //ps.PlotPlotStyles = true;
                                // Specify the plot options

                                LayoutManager.Current.CurrentLayout = lo.LayoutName;
                                pi.Layout = lo.Id;
                                ps.CopyFrom(lo);
                                ps.PrintLineweights = true;
                                ps.PlotTransparency = false;
                                ps.PlotPlotStyles = true;
                                ps.DrawViewportsFirst = true;
                                ps.ShowPlotStyles = true;
                                //PlotStyleTable = GetVauleFromArray("CtbThinnerLinesName")
                                // The PlotSettingsValidator helps create a valid PlotSettings object
                                PlotSettingsValidator psv = PlotSettingsValidator.Current;
                                psv.SetPlotConfigurationName(ps, PrinterName, PaperSize);
                                psv.RefreshLists(ps);
                                psv.SetPlotWindowArea(ps, window);
                                psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                psv.SetUseStandardScale(ps, true);
                                psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                                psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                                psv.SetCurrentStyleSheet(ps, "monochrome.ctb");
                                ////
                                //var e = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("PSTYLEMODE");
                                //var a = db.PlotStyleMode;
                                //var b = psv.GetPlotStyleSheetList();
                                //foreach (String CTB in b)
                                //{
                                //    var c = CTB;
                                //}
                                //if (a)
                                //{
                                //     psv.SetCurrentStyleSheet(ps, "monochrome.ctb");

                                //}
                                //else
                                //{
                                //    psv.SetCurrentStyleSheet(ps, "monochrome.stb");
                                //}


                                psv.SetPlotCentered(ps, true);

                                pi.OverrideSettings = ps;
                                piv.Validate(pi);
                                //if (selectedProcessName != "")
                                //{
                                //    OutPath = GValues.pdfPath + "\\" + selectedProductCode + "-process-" + selectedProcessName + "-" + tableDict["processSop"]["tableHandleId"] + ".pdf";
                                //}
                                //else
                                //{
                                //    OutPath = GValues.pdfPath + "\\" + selectedProductCode + ".pdf";
                                //}
                                OutPath = GValues.pdfPath + "\\" + selectedProductCode + ".pdf";
                                pe.BeginDocument(pi, doc.Name, null, 1, true, OutPath); // Create document for the first page

                                // Plot the window
                                pe.BeginPage(ppi, pi, true, null);
                                pe.BeginGenerateGraphics(null);
                                ppd.SheetProgressPos = 50;
                                pe.EndGenerateGraphics(null);

                                // Finish the sheet
                                pe.EndPage(null);
                                ppd.SheetProgressPos = 100;
                                ppd.PlotProgressPos = 100; //+= Convert.ToInt32(100 / BlocksToPlot.Count);
                                ppd.OnEndSheet();
                                // Finish the document and finish the plot
                                pe.EndDocument(null);

                                ppd.PlotProgressPos = 100;
                                ppd.OnEndPlot();
                                pe.EndPlot(null);
                                ed.WriteMessage("\nPlot completed successfully!\n\n");
                                ps.Dispose();
                                pe.Dispose();
                                ppd.Dispose();
                            }
                        }
                        //Task.Delay(2000);

                        //doc.CloseAndDiscard();

                        // 关闭绘图过程
                        //PlotFactory.ProcessPlotState = PlotState.Cancel;
                    }
                    else
                    {
                        ed.WriteMessage("\nAnother plot is in progress.\n\n");
                    }
                    tr.Commit();
                    tr.Dispose();
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.PlotSettings): DisposableWrapper
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.ViewTableRecord): DisposableWrapper

                }
                //Application.SetSystemVariable("BACKGROUNDPLOT", SysVarBackPlot);
                //if (this.pdfform != null)
                //{
                //    this.pdfform.Close();
                //    this.pdfform = null;

                //}
                //pdfform = new PdfProgressForm(selectedProductCode, new Action<int>((r) =>
                //{
                //    if (r == 1)
                //    {
                //        //uploadPdf();
                //        //this.pdfform.Close();
                //    }
                //    else
                //    {
                //        //ed.WriteMessage("\n上传pdf失败");
                //    }
                //}));
                //// 显示 Windows Form 窗口
                //Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, pdfform);
                //pdfform.beginProcess();

                //for (int i = 0; i <= 100; i++)
                //{
                //    SimpleProgressBar bar = new SimpleProgressBar();
                //    bar.Show();
                //    bar.UpdateProgress(100);

                //    //Thread.Sleep(100); // 模拟任务的执行时间
                //    Task.Delay(TimeSpan.FromSeconds(2)).Wait(); //等待2秒
                //    String filePath = GValues.pdfPath + "\\selectDWGWindow.pdf";
                //    // 判断文件是否存在
                //    if (File.Exists(filePath))
                //    {
                //        bar.Close();
                //        DialogResult res = MessageBox.Show("PDF文件已经生成，确认要上传吗？", "上传提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                //        if (res == DialogResult.OK)  //1为确定，2为取消,...
                //        {
                //            //按OK后，执行语句；
                //            if (checkProductCode)
                //            {
                //                uploadPdf();
                //            }
                //        }
                //        if (res == DialogResult.Cancel)  //1为确定，2为取消,...
                //        {
                //            //按Cancel后，执行语句；
                //        }

                //        break;
                //        //Thread.Sleep(2000);
                //        //uploadPdf();
                //        //ed.WriteMessage("上传完成！");
                //    }
                // }

            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {

            }
            finally
            {

            }



        }


        public void BlockToNewDwg()
        {
            // 获取当前文档和数据库
            Document doc = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            // 提示用户选择一个块参照
            //PromptEntityOptions peo = new PromptEntityOptions("\n选择一个块参照: ");
            //peo.SetRejectMessage("\n选择的不是图形，请重新选择。");
            ////peo.AddAllowedClass(typeof(BlockReference), true);
            //PromptEntityResult per = ed.GetEntity(peo);

            //// 选择图形
            //PromptEntityOptions peo = new PromptEntityOptions("\n选择图形: ");
            //peo.SetRejectMessage("\n选择的不是图形，请重新选择。");
            ////peo.AddAllowedClass(typeof(BlockReference), true);//图片选择属性

            PromptPointOptions peo = new PromptPointOptions("\nSelect first corner of plot area: ");
            peo.AllowNone = false;
            PromptPointResult per = ed.GetPoint(peo);



            if (per.Status != PromptStatus.OK)
            {
                return;
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 打开块表
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                // 遍历模型空间、图纸空间等所有块表记录
                foreach (ObjectId btrId in bt)
                {

                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead);
                    foreach (ObjectId objId in btr)
                    {
                        Entity ent = (Entity)tr.GetObject(objId, OpenMode.ForRead);
                        if (ent is BlockReference)
                        {
                            BlockReference blockRef = ent as BlockReference;

                            //// 获取选择的块参照
                            //BlockReference blkRef = tr.GetObject(per.ObjectId, OpenMode.ForRead) as BlockReference;
                            //if (blkRef == null)
                            //{
                            //    ed.WriteMessage("\n选择的对象不是块参照。");
                            //    tr.Commit();
                            //    return;
                            //}

                            //// 获取块定义
                            //BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                            BlockTableRecord btr1 = (BlockTableRecord)tr.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead);

                            // 创建新的数据库
                            Database newDb = new Database(true, false);

                            // 复制块定义到新数据库
                            ObjectIdCollection ids = new ObjectIdCollection();
                            ids.Add(btr1.ObjectId);
                            db.WblockCloneObjects(ids, newDb.BlockTableId, new IdMapping(), DuplicateRecordCloning.Replace, false);

                            // 复制块内对象到新数据库
                            foreach (ObjectId objId1 in btr1)
                            {
                                Entity ent1 = tr.GetObject(objId, OpenMode.ForRead) as Entity;
                                if (ent1 != null)
                                {
                                    ids = new ObjectIdCollection();
                                    ids.Add(objId1);
                                    db.WblockCloneObjects(ids, newDb.BlockTableId, new IdMapping(), DuplicateRecordCloning.Replace, false);
                                }
                            }

                            // 保存新数据库为新的 DWG 文件
                            string newDwgPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(db.Filename), btr1.Name + ".dwg");
                            newDb.SaveAs(newDwgPath, DwgVersion.AC1800);

                            // 释放新数据库资源
                            newDb.Dispose();



                        }
                    }

                }




                tr.Commit();
            }

            ed.WriteMessage("\n块已成功导出到新的 DWG 文件: {0}");
        }

 public void ConvertDwgToPdf()
    {
        string directoryPath = @"C:\plot2pdf"; // 替换为你的 DWG 文件目录
        string pdfOutputDirectory = @"C:\plot2pdf2upload"; // 替换为你的 PDF 输出目录

        // 确保输出目录存在
        if (!Directory.Exists(pdfOutputDirectory))
        {
            Directory.CreateDirectory(pdfOutputDirectory);
        }

        // 获取所有 DWG 文件
        string[] dwgFiles = Directory.GetFiles(directoryPath, "*.dwg");

        foreach (string dwgFile in dwgFiles)
        {
            string pdfFileName = Path.GetFileNameWithoutExtension(dwgFile) + ".pdf";
            string pdfFilePath = Path.Combine(pdfOutputDirectory, pdfFileName);

            // 打印 DWG 文件为 PDF
            PrintToPDF(dwgFile, pdfFilePath);
        }
    }


public void PrintToPDF(string dwgFilePath, string pdfFilePath)
{
    // 打开 DWG 文件
    Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.Open(dwgFilePath, false);
    Database acDb = acDoc.Database;

    using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
    {
        // 获取当前布局
        LayoutManager manager = LayoutManager.Current;
        Layout acLayout = acTrans.GetObject(manager.GetLayoutId(manager.CurrentLayout), OpenMode.ForRead) as Layout;

        // 创建 PlotInfo 和 PlotSettings
        using (PlotInfo acPlInfo = new PlotInfo())
        {
            acPlInfo.Layout = acLayout.ObjectId;

            using (PlotSettings acPlSet = new PlotSettings(acLayout.ModelType))
            {
                acPlSet.CopyFrom(acLayout);
                PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;

                // 设置打印区域为图形范围
                acPlSetVdr.SetPlotType(acPlSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);

                // 设置打印比例为自适应
                acPlSetVdr.SetUseStandardScale(acPlSet, true);
                acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit);

                // 设置居中打印
                acPlSetVdr.SetPlotCentered(acPlSet, true);

                // 设置打印机为 PDF 打印机
                string deviceName = "DWG To PDF.pc3"; // 确保此打印机配置存在
                string canonicalMediaName = "ISO_A4_(210.00_x_297.00_mm)"; // 根据需要选择纸张类型
                acPlSetVdr.SetPlotConfigurationName(acPlSet, deviceName, canonicalMediaName);

                acPlInfo.OverrideSettings = acPlSet;

                using (PlotInfoValidator acPlInfoVdr = new PlotInfoValidator() { MediaMatchingPolicy = MatchingPolicy.MatchEnabled })
                {
                    acPlInfoVdr.Validate(acPlInfo);

                    // 开始打印
                    using (PlotEngine acPlEng = PlotFactory.CreatePublishEngine())
                    {
                        using (PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false, 1, true))
                        {
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "打印中，请稍候……");
                            acPlProgDlg.IsVisible = true;

                            acPlEng.BeginPlot(acPlProgDlg, null);
                            acPlEng.BeginDocument(acPlInfo, acDoc.Name, null, 1, true, pdfFilePath);

                            using (PlotPageInfo acPlPageInfo = new PlotPageInfo())
                            {
                                acPlEng.BeginPage(acPlPageInfo, acPlInfo, true, null);
                                acPlEng.BeginGenerateGraphics(null);
                                acPlEng.EndGenerateGraphics(null);
                                acPlEng.EndPage(null);
                            }

                            acPlEng.EndDocument(null);
                            acPlEng.EndPlot(null);
                        }
                    }
                }
            }
        }

        acTrans.Commit();
    }

    acDoc.CloseAndDiscard();
}

        public void TestOpenFile2PDF()
        {
            String selectedProductCode = "block-file-test";
            String OutPath = "";
            String processHandleId = "";
            Boolean checkProductCode = false;
            Directory.CreateDirectory(GValues.pdfPath);
            Dictionary<String, Dictionary<String, String>> tableDict = new Dictionary<string, Dictionary<string, string>>();
            SetObject setObject = new SetObject();
            setObject.initTableDictData(tableDict);
            // 判断文件是否存在
            //if (File.Exists(OutPath))
            //{
            //    try
            //    {
            //        // 尝试删除文件
            //        File.Delete(OutPath);
            //        outMsg.AddMsg("文件已删除。");
            //    }
            //    catch (IOException ex)
            //    {                    // IO异常处理
            //        outMsg.AddMsg("无法删除文件: " + ex.Message);
            //    }
            //}
            try
            {

                String BlockName;
                String PrinterName = "DWG To PDF.pc3";

                String PaperSize = "ISO_full_bleed_A4_(210.00_x_297.00_MM)";//"ISO_A4_(210.00_x_297.00_MM)";
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                Database db = doc.Database;
                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                //改成块开始
                PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner of plot area: ");
                ppo.AllowNone = false;
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK)
                    return;
                Point3d first1 = ppr.Value;
                PromptCornerOptions pco = new PromptCornerOptions("\nSelect second corner of plot area: ", first1);
                ppr = ed.GetCorner(pco);
                if (ppr.Status != PromptStatus.OK)
                    return;
                Point3d second2 = ppr.Value;
                //改成块结束

                ///wcs 2 ucs
                ///
                //Vector3d vect = db.Ucsorg.GetVectorTo(new Point3d(0,0,0));
                //Matrix3d matWCS2UCS = Matrix3d.WorldToPlane(vect);
                //Point3d second = second1.TransformBy(matWCS2UCS);
                //Point3d first = first1.TransformBy(matWCS2UCS);
                ////


                //Matrix3d wcs2ucs = doc.Editor.CurrentUserCoordinateSystem.Inverse();
                //Point3d ucsPoint = worldPoint.TransformBy(wcs2ucs);

                //wcs 2 dcs
                //
                //
                // Gets the current view
                //ViewTableRecord acView = doc.Editor.GetCurrentView();
                ////Extents3d eExtents = new Extents3d(new Point3d(0, 0, 0), new Point3d(630, 445.5, 0));
                //Extents3d eExtents = new Extents3d(first, second);
                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                               acView.ViewDirection,
                //                               acView.Target) * matWCS2DCS;

                //// Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);

                //
                //ViewTableRecord acView = doc.Editor.GetCurrentView();

                //Extents3d eExtents = new Extents3d(first, second);

                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                                acView.ViewDirection,
                //                                acView.Target) * matWCS2DCS;

                ////Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);
                //var wcsWindow = new Extents2d(eExtents.MinPoint.X, eExtents.MinPoint.Y,
                //                                        eExtents.MaxPoint.X, eExtents.MaxPoint.Y);

                //
                // 获取当前视图方向
                Vector3d viewDir = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;

                // 获取当前视图位置
                Point3d viewPos = ed.GetCurrentView().Target;

                // 构造视图变换矩阵
                Matrix3d viewTransform = Matrix3d.WorldToPlane(viewDir).Inverse();
                //viewTransform = Matrix3d.Displacement(viewPos.GetAsVector()) * viewTransform;

                //// 将WCS坐标转换为DCS坐标
                Point3d first = first1.TransformBy(viewTransform);
                Point3d second = second2.TransformBy(viewTransform);


                ///====

                // Transform from UCS to DCS
                ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                double[] firres = new double[] { 0, 0, 0 };
                double[] secres = new double[] { 0, 0, 0 };
                // Transform the first point...
                acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                // ... and the second
                acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                // We can safely drop the Z-coord at this stage
                Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                //Object SysVarBackPlot = Application.GetSystemVariable("BACKGROUNDPLOT");
                //Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                Transaction tr = db.TransactionManager.StartTransaction();
                using (tr)
                {
                    // 打开图层表
                    LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                    // 遍历所有图层
                    foreach (ObjectId layerId in lt)
                    {
                        // 打开图层表记录
                        LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForRead);

                        // 检查图层是否锁定
                        if (ltr.IsLocked)
                        {
                            // 解锁图层
                            ltr.UpgradeOpen();
                            ltr.IsLocked = false;
                            ltr.DowngradeOpen();
                        }
                    }
                    // We'll be plotting the current layout
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);

                    // 定义过滤条件，设置仅选择BlockReference

                    //SelectionFilter filter = new SelectionFilter(new TypedValue[]
                    //{
                    //    new TypedValue((int)DxfCode.Start, "TEXT") // "INSERT"代表图块引用
                    //});
                    // 使用选取窗口和过滤条件进行选择
                    PromptSelectionResult selectionResult = ed.SelectCrossingWindow(first, second);

                    // 检查选择结果
                    if (selectionResult.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage("\n未选择对象或操作取消。");
                        return;
                    }
                    //Dictionary<String, String> fieldDict = new Dictionary<string, string>();
                    SelectionSet sSet = selectionResult.Value;
                    ObjectId[] selectedIds = sSet.GetObjectIds();  // 获取选择对象的ObjectiID数组.
                    foreach (ObjectId objId in selectedIds)
                    {
                        Entity entity = tr.GetObject(objId, OpenMode.ForRead) as Entity;

                        if (entity is Table)
                        {

                            Table table = entity as Table;
                            // 你现在可以使用table对象了
                            // ...
                            processHandleId = table.Handle.Value.ToString();
                            if (table.XData != null)
                            {
                                Dictionary<String, String> xDataDict = new Dictionary<string, string>();
                                String tableType = "none";
                                ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                // 遍历ResultBuffer以查看数据
                                foreach (TypedValue tv in rb)
                                {
                                    switch ((DxfCode)tv.TypeCode)
                                    {
                                        case DxfCode.ExtendedDataRegAppName:
                                            var a = tv.Value.ToString();
                                            ed.WriteMessage("\n APP Code :" + a);
                                            break;
                                        case DxfCode.ExtendedDataAsciiString:
                                            var b = tv.Value.ToString();
                                            if (b.IndexOf("tableType:") != -1)
                                            {
                                                String[] cc = b.Split(':');
                                                if (cc[1] == "processSop")
                                                {
                                                    tableType = "processSop";
                                                    xDataDict["processSop"] = "true"; //SOP图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "processBom")
                                                {
                                                    tableType = "processBom";
                                                    xDataDict["processBom"] = "true"; //工艺图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "productBom")
                                                {
                                                    tableType = "productBom";
                                                    xDataDict["productBom"] = "true"; //产品图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                            }
                                            else if (b.IndexOf("processName:") != -1)
                                            {
                                                ed.WriteMessage("\n Process Name :" + b);
                                                String[] cc = b.Split(':');
                                                //selectedProcessName = cc[1];
                                                xDataDict["processName"] = cc[1];
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            else if (b.IndexOf("productCode:") != -1)
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                String[] cc = b.Split(':');
                                                //selectedProductCode = cc[1];
                                                xDataDict["productCode"] = cc[1];
                                                checkProductCode = true;
                                            }
                                            else
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                //selectedProductCode = b;
                                                checkProductCode = true;
                                                xDataDict["productCode"] = b;
                                                xDataDict["oldTable"] = "true";
                                                tableType = "oldTable";
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            break;
                                        // 其他类型的DXF组码...

                                    }
                                }
                                tableDict[tableType] = xDataDict;
                            }
                            else
                            {
                                ed.WriteMessage("\n实体没有扩展数据！");
                            }
                        }

                    }
                    if (!checkProductCode)
                    {
                        ed.WriteMessage("\n选择框内没有定义工艺数据！");
                        //return;
                    }
                    else
                    {
                        if (tableDict["productBom"]["productBom"] == "true" && tableDict["processBom"]["processBom"] == "false" && tableDict["processSop"]["processSop"] == "false")
                        {
                            ed.WriteMessage("\n选择框内没有定义工艺数据！");
                            //return;
                        }
                    }

                    Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                    if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                    {
                        PlotEngine pe = PlotFactory.CreatePublishEngine();
                        using (pe)
                        {
                            PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true);
                            using (ppd)
                            {
                                int numSheet = 1;
                                // Setting up the PlotProgress dialog
                                ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                                ppd.LowerPlotProgressRange = 0;
                                ppd.UpperPlotProgressRange = 100;
                                ppd.PlotProgressPos = 0;


                                ppd.OnBeginPlot();
                                ppd.IsVisible = true;
                                pe.BeginPlot(ppd, null);

                                ppd.StatusMsgString = "Plotting block 1";
                                ppd.OnBeginSheet(); //????
                                ppd.LowerSheetProgressRange = 0;
                                ppd.UpperSheetProgressRange = 100;
                                ppd.SheetProgressPos = 0;

                                PlotInfoValidator piv = new PlotInfoValidator();
                                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                PlotPageInfo ppi = new PlotPageInfo();
                                PlotInfo pi = new PlotInfo();
                                //BlockReference blk = gblk.BlockRef;
                                //Layout lo = btr.LayoutObj;

                                //// Getting coodinates of window to plot
                                //Extents3d ext = (Extents3d)blk.Bounds;
                                //Point3d first = ext.MaxPoint;
                                //Point3d second = ext.MinPoint;
                                //ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                                //double[] firres = new double[] { 0, 0, 0 };
                                //double[] secres = new double[] { 0, 0, 0 };
                                //acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                                //acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                                //Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                                // We need a PlotSettings object based on the layout settings which we then customize
                                PlotSettings ps = new PlotSettings(lo.ModelType);
                                //ps.PlotPlotStyles = true;
                                // Specify the plot options

                                LayoutManager.Current.CurrentLayout = lo.LayoutName;
                                pi.Layout = lo.Id;
                                ps.CopyFrom(lo);
                                ps.PrintLineweights = true;
                                ps.PlotTransparency = false;
                                ps.PlotPlotStyles = true;
                                ps.DrawViewportsFirst = true;
                                ps.ShowPlotStyles = true;
                                //PlotStyleTable = GetVauleFromArray("CtbThinnerLinesName")
                                // The PlotSettingsValidator helps create a valid PlotSettings object
                                PlotSettingsValidator psv = PlotSettingsValidator.Current;
                                psv.SetPlotConfigurationName(ps, PrinterName, PaperSize);
                                psv.RefreshLists(ps);
                                psv.SetPlotWindowArea(ps, window);
                                psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                psv.SetUseStandardScale(ps, true);
                                psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                                psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                                psv.SetCurrentStyleSheet(ps, "monochrome.ctb");
                                ////
                                //var e = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("PSTYLEMODE");
                                //var a = db.PlotStyleMode;
                                //var b = psv.GetPlotStyleSheetList();
                                //foreach (String CTB in b)
                                //{
                                //    var c = CTB;
                                //}
                                //if (a)
                                //{
                                //     psv.SetCurrentStyleSheet(ps, "monochrome.ctb");

                                //}
                                //else
                                //{
                                //    psv.SetCurrentStyleSheet(ps, "monochrome.stb");
                                //}


                                psv.SetPlotCentered(ps, true);

                                pi.OverrideSettings = ps;
                                piv.Validate(pi);
                                //if (selectedProcessName != "")
                                //{
                                //    OutPath = GValues.pdfPath + "\\" + selectedProductCode + "-process-" + selectedProcessName + "-" + tableDict["processSop"]["tableHandleId"] + ".pdf";
                                //}
                                //else
                                //{
                                //    OutPath = GValues.pdfPath + "\\" + selectedProductCode + ".pdf";
                                //}
                                OutPath = GValues.pdfPath + "\\" + selectedProductCode + ".pdf";
                                pe.BeginDocument(pi, doc.Name, null, 1, true, OutPath); // Create document for the first page

                                // Plot the window
                                pe.BeginPage(ppi, pi, true, null);
                                pe.BeginGenerateGraphics(null);
                                ppd.SheetProgressPos = 50;
                                pe.EndGenerateGraphics(null);

                                // Finish the sheet
                                pe.EndPage(null);
                                ppd.SheetProgressPos = 100;
                                ppd.PlotProgressPos = 100; //+= Convert.ToInt32(100 / BlocksToPlot.Count);
                                ppd.OnEndSheet();
                                // Finish the document and finish the plot
                                pe.EndDocument(null);

                                ppd.PlotProgressPos = 100;
                                ppd.OnEndPlot();
                                pe.EndPlot(null);
                                ed.WriteMessage("\nPlot completed successfully!\n\n");
                                ps.Dispose();
                                pe.Dispose();
                                ppd.Dispose();
                            }
                        }
                        //Task.Delay(2000);

                        //doc.CloseAndDiscard();

                        // 关闭绘图过程
                        //PlotFactory.ProcessPlotState = PlotState.Cancel;
                    }
                    else
                    {
                        ed.WriteMessage("\nAnother plot is in progress.\n\n");
                    }
                    tr.Commit();
                    tr.Dispose();
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.PlotSettings): DisposableWrapper
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.ViewTableRecord): DisposableWrapper

                }
                //Application.SetSystemVariable("BACKGROUNDPLOT", SysVarBackPlot);
                //if (this.pdfform != null)
                //{
                //    this.pdfform.Close();
                //    this.pdfform = null;

                //}
                //pdfform = new PdfProgressForm(selectedProductCode, new Action<int>((r) =>
                //{
                //    if (r == 1)
                //    {
                //        //uploadPdf();
                //        //this.pdfform.Close();
                //    }
                //    else
                //    {
                //        //ed.WriteMessage("\n上传pdf失败");
                //    }
                //}));
                //// 显示 Windows Form 窗口
                //Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, pdfform);
                //pdfform.beginProcess();

                //for (int i = 0; i <= 100; i++)
                //{
                //    SimpleProgressBar bar = new SimpleProgressBar();
                //    bar.Show();
                //    bar.UpdateProgress(100);

                //    //Thread.Sleep(100); // 模拟任务的执行时间
                //    Task.Delay(TimeSpan.FromSeconds(2)).Wait(); //等待2秒
                //    String filePath = GValues.pdfPath + "\\selectDWGWindow.pdf";
                //    // 判断文件是否存在
                //    if (File.Exists(filePath))
                //    {
                //        bar.Close();
                //        DialogResult res = MessageBox.Show("PDF文件已经生成，确认要上传吗？", "上传提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                //        if (res == DialogResult.OK)  //1为确定，2为取消,...
                //        {
                //            //按OK后，执行语句；
                //            if (checkProductCode)
                //            {
                //                uploadPdf();
                //            }
                //        }
                //        if (res == DialogResult.Cancel)  //1为确定，2为取消,...
                //        {
                //            //按Cancel后，执行语句；
                //        }

                //        break;
                //        //Thread.Sleep(2000);
                //        //uploadPdf();
                //        //ed.WriteMessage("上传完成！");
                //    }
                // }

            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {

            }
            finally
            {

            }



        }
         public void ReadDwg()
        {
            // 指定 DWG 文件的路径
            string filePath = @"D:\工程图\11HZXC304-1.dwg";
            String PrinterName = "DWG To PDF.pc3";
            String PaperSize = "ISO_full_bleed_A4_(210.00_x_297.00_MM)";//"ISO_A4_(210.00_x_297.00_MM)";
            DocumentCollection docMgr = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
            Database db = null;
            Document doc = null;
            try
            {
               
                // 打开 DWG 文件
                doc = docMgr.Open(filePath, false);
                db = doc.Database;
                Editor ed = doc.Editor;
                // 启动事务
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    // 打开块表
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                    // 打开模型空间块表记录
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);

                    // 遍历模型空间中的所有对象
                    foreach (ObjectId objId in btr)
                    {
                        // 获取对象
                        Entity ent = (Entity)tr.GetObject(objId, OpenMode.ForRead);
                        if (ent is BlockReference)
                        {
                            BlockReference blockRef = ent as BlockReference;
                            Point3d position = blockRef.Position;
                            // 获取块定义的基点
                            btr = tr.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;

                            string code = "";

                            // 遍历块引用中的所有属性
                            foreach (ObjectId attId in blockRef.AttributeCollection)
                            {
                                AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead);
                                if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                                {
                                    code = attRef.TextString;
                                    //result["图号"] = attRef.TextString;
                                }
                                if (attRef.Tag.IndexOf("製程") != -1)
                                {
                                    //result[attRef.Tag] = attRef.TextString;
                                }
                            }
                            // 获取块引用所在的图层
                            string layerName = blockRef.Layer;
                            // 获取块的名称
                            string blockName = blockRef.Name;
                            // 输出块引用的信息
                            //ed.WriteMessage("\n在图层 {0} 找到块引用: {1}", layerName, blockName);
                            //SelectBlock2Pdf block2Pdf = new SelectBlock2Pdf();
                           //this.PlotBlockColToPDF1(doc,blockRef.DynamicBlockTableRecord.Database.Extmin, blockRef.DynamicBlockTableRecord.Database.Extmax, code);
                            Point3d first1 = blockRef.DynamicBlockTableRecord.Database.Extmin;
                            Point3d second2 = blockRef.DynamicBlockTableRecord.Database.Extmax;

                           //开始打印pdf
                            //
                            // 获取当前视图方向
                            Vector3d viewDir = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;

                            // 获取当前视图位置
                            Point3d viewPos = ed.GetCurrentView().Target;

                            // 构造视图变换矩阵
                            Matrix3d viewTransform = Matrix3d.WorldToPlane(viewDir).Inverse();
                            //viewTransform = Matrix3d.Displacement(viewPos.GetAsVector()) * viewTransform;

                            //// 将WCS坐标转换为DCS坐标
                            Point3d first = first1.TransformBy(viewTransform);
                            Point3d second = second2.TransformBy(viewTransform);


                            ///====

                            // Transform from UCS to DCS
                            ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                            double[] firres = new double[] { 0, 0, 0 };
                            double[] secres = new double[] { 0, 0, 0 };
                            // Transform the first point...
                            acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                            // ... and the second
                            acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                            // We can safely drop the Z-coord at this stage
                            Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                            Transaction tr1 = db.TransactionManager.StartTransaction();
                            using (tr1)
                            {
                                // 打开图层表
                                LayerTable lt = (LayerTable)tr1.GetObject(db.LayerTableId, OpenMode.ForRead);

                                // 遍历所有图层
                                foreach (ObjectId layerId in lt)
                                {
                                    // 打开图层表记录
                                    LayerTableRecord ltr = (LayerTableRecord)tr1.GetObject(layerId, OpenMode.ForRead);

                                    // 检查图层是否锁定
                                    if (ltr.IsLocked)
                                    {
                                        // 解锁图层
                                        ltr.UpgradeOpen();
                                        ltr.IsLocked = false;
                                        ltr.DowngradeOpen();
                                    }
                                }
                                // We'll be plotting the current layout
                                BlockTableRecord btr1 = (BlockTableRecord)tr1.GetObject(db.CurrentSpaceId, OpenMode.ForRead);

                                // 定义过滤条件，设置仅选择BlockReference

                                //SelectionFilter filter = new SelectionFilter(new TypedValue[]
                                //{
                                //    new TypedValue((int)DxfCode.Start, "TEXT") // "INSERT"代表图块引用
                                //});
                                // 使用选取窗口和过滤条件进行选择
                                PromptSelectionResult selectionResult = ed.SelectCrossingWindow(first, second);

                                // 检查选择结果
                                if (selectionResult.Status != PromptStatus.OK)
                                {
                                    ed.WriteMessage("\n未选择对象或操作取消。");
                                    return;
                                }
                                //Dictionary<String, String> fieldDict = new Dictionary<string, string>();
                                SelectionSet sSet = selectionResult.Value;
                                ObjectId[] selectedIds = sSet.GetObjectIds();  // 获取选择对象的ObjectiID数组.
                                Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                                if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                                {
                                    PlotEngine pe = PlotFactory.CreatePublishEngine();
                                    using (pe)
                                    {
                                        PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true);
                                        using (ppd)
                                        {
                                            int numSheet = 1;
                                            // Setting up the PlotProgress dialog
                                            ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
                                            ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                                            ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                                            ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                                            ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                                            ppd.LowerPlotProgressRange = 0;
                                            ppd.UpperPlotProgressRange = 100;
                                            ppd.PlotProgressPos = 0;


                                            ppd.OnBeginPlot();
                                            ppd.IsVisible = true;
                                            pe.BeginPlot(ppd, null);

                                            ppd.StatusMsgString = "Plotting block 1";
                                            ppd.OnBeginSheet(); //????
                                            ppd.LowerSheetProgressRange = 0;
                                            ppd.UpperSheetProgressRange = 100;
                                            ppd.SheetProgressPos = 0;

                                            PlotInfoValidator piv = new PlotInfoValidator();
                                            piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                            PlotPageInfo ppi = new PlotPageInfo();
                                            PlotInfo pi = new PlotInfo();
                                            PlotSettings ps = new PlotSettings(lo.ModelType);
                                            LayoutManager.Current.CurrentLayout = lo.LayoutName;
                                            pi.Layout = lo.Id;
                                            ps.CopyFrom(lo);
                                            ps.PrintLineweights = true;
                                            ps.PlotTransparency = false;
                                            ps.PlotPlotStyles = true;
                                            ps.DrawViewportsFirst = true;
                                            ps.ShowPlotStyles = true;
                                            //PlotStyleTable = GetVauleFromArray("CtbThinnerLinesName")
                                            // The PlotSettingsValidator helps create a valid PlotSettings object
                                            PlotSettingsValidator psv = PlotSettingsValidator.Current;
                                            psv.SetPlotConfigurationName(ps, PrinterName, PaperSize);
                                            psv.RefreshLists(ps);
                                            psv.SetPlotWindowArea(ps, window);
                                            psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                            psv.SetUseStandardScale(ps, true);
                                            psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                                            psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                                            psv.SetCurrentStyleSheet(ps, "monochrome.ctb");

                                            psv.SetPlotCentered(ps, true);

                                            pi.OverrideSettings = ps;
                                            piv.Validate(pi);
                                            //if (selectedProcessName != "")
                                            //{
                                            //    OutPath = GValues.pdfPath + "\\" + selectedProductCode + "-process-" + selectedProcessName + "-" + tableDict["processSop"]["tableHandleId"] + ".pdf";
                                            //}
                                            //else
                                            //{
                                            //    OutPath = GValues.pdfPath + "\\" + selectedProductCode + ".pdf";
                                            //}
                                            String OutPath = GValues.pdfPath + "\\" + code + ".pdf";
                                            pe.BeginDocument(pi, doc.Name, null, 1, true, OutPath); // Create document for the first page

                                            // Plot the window
                                            pe.BeginPage(ppi, pi, true, null);
                                            pe.BeginGenerateGraphics(null);
                                            ppd.SheetProgressPos = 50;
                                            pe.EndGenerateGraphics(null);

                                            // Finish the sheet
                                            pe.EndPage(null);
                                            ppd.SheetProgressPos = 100;
                                            ppd.PlotProgressPos = 100; //+= Convert.ToInt32(100 / BlocksToPlot.Count);
                                            ppd.OnEndSheet();
                                            // Finish the document and finish the plot
                                            pe.EndDocument(null);

                                            ppd.PlotProgressPos = 100;
                                            ppd.OnEndPlot();
                                            pe.EndPlot(null);
                                            ed.WriteMessage("\nPlot completed successfully!\n\n");
                                            ps.Dispose();
                                            pe.Dispose();
                                            ppd.Dispose();
                                        }
                                    }
                                }
                                else
                                {
                                    ed.WriteMessage("\nAnother plot is in progress.\n\n");
                                }
                                tr.Commit();
                                tr.Dispose();
                            }

                            //打印pdf结束
                        }

                        // 提交事务
                        tr.Commit();
                    }
                }
            }
            catch (System.Exception ex)
            {

            }
            finally
            {
                if (db != null)
                {
                    // 关闭数据库对象
                    db.Dispose();
                }
                if (doc != null)
                {
                    // 关闭文档
                    doc.CloseAndDiscard();
                    Console.WriteLine("DWG 文件已关闭。");
                }
            }
        }


    }
}
